package org.jeecg.modules.stCaip.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;

import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.kuawcsFs.entity.AgKuawcsFs;
import org.jeecg.modules.kuawcsFs.service.IAgKuawcsFsService;
import org.jeecg.modules.renlmd.entity.HqStRenlmdMx;
import org.jeecg.modules.renlmd.service.IHqStRenlmdMxService;
import org.jeecg.modules.shuibdb.entity.HqShuibdb;
import org.jeecg.modules.stCaip.entity.HqStCaip;
import org.jeecg.modules.stCaip.service.IHqStCaipService;
import org.jeecg.modules.stCaip.vo.CatalogAndCaiP;
import org.jeecg.modules.stCaip.vo.LidaRtn;
import org.jeecg.modules.stCaip.vo.ReceiveCaipData;
import org.jeecg.modules.system.entity.SysDictItem;
import org.jeecg.modules.system.service.ISysDictItemService;
import org.jeecg.modules.xiaonv.service.XiaoNiuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 菜品详情
 * @Author: jeecg-boot
 * @Date: 2020-10-26
 * @Version: V1.0
 */
@Api(tags = "菜品详情")
@RestController
@RequestMapping("/stCaip/hqStCaip")
@Slf4j
public class HqStCaipController extends JeecgController<HqStCaip, IHqStCaipService> {
    @Autowired
    private IHqStCaipService hqStCaipService;

    @Autowired
    ISysDictItemService sysDictItemService;

    @Autowired
	XiaoNiuService xiaoNiuService;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    private IHqStRenlmdMxService hqStRenlmdMxService;

    // 食堂查询在线人数
    @GetMapping(value = "/queryShitdqrs")
    public Result<?> queryShitdqrs(String shitId)
    {
        Calendar calendar = DateUtils.getCalendar();
        calendar.add(Calendar.MINUTE, - 90);
        String startTime = DateUtils.formatDate(calendar.getTime(), "yyyy-MM-dd HH:mm:ss");
        String endTime = DateUtils.formatDateTime();

        int jinr = 0;
        int lik = 0;
        List<HqStRenlmdMx> list = hqStRenlmdMxService.list(new LambdaQueryWrapper<HqStRenlmdMx>().between(HqStRenlmdMx::getShangbsj, startTime, endTime));
        for (HqStRenlmdMx hqStRenlmdMx: list
             ) {
            int a = Integer.parseInt(hqStRenlmdMx.getJinrrs() == null ? "0" :  hqStRenlmdMx.getJinrrs());
            int b = Integer.parseInt(hqStRenlmdMx.getLikrs() == null ? "0" :  hqStRenlmdMx.getLikrs());

            jinr += a;
            lik += b;
        }

        Result result = new Result();
        result.setSuccess(true);
        result.setResult("三食堂二层: " + Math.abs(jinr - lik) * 3);

        return result;
    }

    // 调用理达接口卡号换账号，理达刷卡时给小牛传的事account_no 所以查询人员订单的时候要转换下才能查到
    /*
    {
    "message": "接口调用成功",
    "result": [
        {
            "MEMBER_NAME": "L190436",
            "IDESTATUS_NO": "S",
            "SERIAL_NO": "7DF0E411",
            "SEX": "男",
            "UPDATE_TIME": 1605146632000,
            "DEPT_NO": "XAGC",
            "STATUS": "正常",
            "MEMBER_ID": "0000041658",
            "ACCOUNT_NO": 47055,
            "VALIDITY": 1833638399000,
            "UP_DATE": 0,
            "MEMBER_CODE": "L190436"
        }
    ],
    "status": 200,
    "totalCount": 1
    }

     */
//    @GetMapping(value = "/queryAccountNoByMemberCode")
    public String queryAccountNoByMemberCode(String kah)
    {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("MEMBER_CODE", kah);

        String rtn = restTemplate.postForObject("http://172.18.51.33:18081/sdata/rest/service/dataapi/rest/c85b624d-50bd-497e-9894-d1a861bdcf79", jsonObject.toJSONString(), String.class);
        LidaRtn lidaRtn = JSON.parseObject(rtn, new TypeReference<LidaRtn>() {});
        return lidaRtn.getResult().get(0).getACCOUNT_NO();
    }

    // 获取售卖的所有菜品，供菜品推荐使用
    @GetMapping(value = "/cpdata")
    public Result<?> cpdata() {
        return Result.ok(xiaoNiuService.cpdata());
    }

    // 消费记录详情
    @GetMapping(value = "/xiaofjlxq")
    public Result<?> xiaofjlxq(String dingdh) {
        return Result.ok(xiaoNiuService.cpdatamx(dingdh));
    }

    // 员工消费记录
    @GetMapping(value = "/yuangxfjl")
    public Result<?> yuangxfjl(String userName, String start, String end) {
        String yuangbh = queryAccountNoByMemberCode(userName);
        return Result.ok(xiaoNiuService.wxLdSsCzXf(yuangbh, start, end));
    }

    // 写入指定食堂
    @PostMapping(value = "/startSync")
    public Result<?> startSync(@RequestBody ReceiveCaipData receiveCaipData) {
        hqStCaipService.remove(new QueryWrapper<HqStCaip>().eq("yingq", receiveCaipData.getYingqId()).eq("shit", receiveCaipData.getShitId()));
        // 删除指定窗口的菜品后再同步
        hqStCaipService.remove(new LambdaQueryWrapper<HqStCaip>().eq(HqStCaip::getChuangk, "1338048489244876801"));

        for (HqStCaip hqStCaip: receiveCaipData.getList()
             ) {
            hqStCaip.setYingq(receiveCaipData.getYingqId());
           // hqStCaip.setShit(receiveCaipData.getShitId());
            // 写死三食堂2层快捷支付窗口
            hqStCaip.setShit("1293079887936823297");
            hqStCaip.setChuangk("1338048489244876801");
            hqStCaip.setFenl("2");
            hqStCaip.setId(UUID.randomUUID().toString().replace("-", ""));
        }

        hqStCaipService.saveBatch(receiveCaipData.getList());


        return Result.ok();
    }

    @GetMapping(value = "/syncXiaonData")
    public Result<?> syncXiaonData(HqStCaip hqStCaip,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        xiaoNiuService.cpdata();
		IPage<HqStCaip> pageList = new Page<>(pageNo, pageSize);
        pageList.setRecords(xiaoNiuService.cpdateshow());

        return Result.ok(pageList);
    }

    String getDictItemText(String itemValue) {
        // 1320694914471251970 shityysd 食堂营业时段
        List<SysDictItem> list = sysDictItemService.selectItemsByMainId("1320694914471251970");
        for (SysDictItem sysDictItem : list
        ) {
            if (sysDictItem.getItemValue().equals(itemValue))
                return sysDictItem.getItemText();
        }

        return "";
    }

    // 给手机端显示类似饿了么，那样色儿的分类菜单数据。入参窗口id
    @GetMapping("/getCatalogAndCaiPData")
    public Result<?> getCatalogAndCaiPData(String chuangk_id, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                           @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        List<CatalogAndCaiP> list = new ArrayList<>();

        List<HqStCaip> listCaiPByChuangK = hqStCaipService.list(new QueryWrapper<HqStCaip>().eq("chuangk", chuangk_id));
        Map<String, List<HqStCaip>> map = listCaiPByChuangK.parallelStream().filter(f->f.getFenl() != null).collect(Collectors.groupingBy(HqStCaip::getFenl));
        map.forEach((k, v) -> {
            CatalogAndCaiP catalogAndCaiP = new CatalogAndCaiP();
            catalogAndCaiP.setCatalogName(getDictItemText(k));
            catalogAndCaiP.setCaiPList(v);
            list.add(catalogAndCaiP);
        });

        return Result.ok(list);
    }

    /**
     * 分页列表查询
     *
     * @param hqStCaip
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "菜品详情-分页列表查询")
    @ApiOperation(value = "菜品详情-分页列表查询", notes = "菜品详情-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(HqStCaip hqStCaip,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<HqStCaip> queryWrapper = QueryGenerator.initQueryWrapper(hqStCaip, req.getParameterMap());
        Page<HqStCaip> page = new Page<HqStCaip>(pageNo, pageSize);
        IPage<HqStCaip> pageList = hqStCaipService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param hqStCaip
     * @return
     */
    @AutoLog(value = "菜品详情-添加")
    @ApiOperation(value = "菜品详情-添加", notes = "菜品详情-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody HqStCaip hqStCaip) {
        hqStCaipService.save(hqStCaip);
        return Result.ok("添加成功！");
    }

    /**
     * 编辑
     *
     * @param hqStCaip
     * @return
     */
    @AutoLog(value = "菜品详情-编辑")
    @ApiOperation(value = "菜品详情-编辑", notes = "菜品详情-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody HqStCaip hqStCaip) {
        hqStCaipService.updateById(hqStCaip);
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "菜品详情-通过id删除")
    @ApiOperation(value = "菜品详情-通过id删除", notes = "菜品详情-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        hqStCaipService.removeById(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "菜品详情-批量删除")
    @ApiOperation(value = "菜品详情-批量删除", notes = "菜品详情-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.hqStCaipService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "菜品详情-通过id查询")
    @ApiOperation(value = "菜品详情-通过id查询", notes = "菜品详情-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        HqStCaip hqStCaip = hqStCaipService.getById(id);
        if (hqStCaip == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(hqStCaip);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param hqStCaip
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, HqStCaip hqStCaip) {
        return super.exportXls(request, hqStCaip, HqStCaip.class, "菜品详情");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, HqStCaip.class);
    }

}
